<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<table id="tbl">
		<thead></thead>
		<tbody>
			<tr>
				<td>iphone6</td>
				<td>4488</td>
				<td>
					<button>-</button>
					<span>1</span>
					<button>+</button>
				</td>
				<td>4488</td>
			</tr>
			<tr>
				<td>iphone7</td>
				<td>5488</td>
				<td>
					<button>-</button>
					<span>1</span>
					<button>+</button>
				</td>
				<td>5488</td>
			</tr>
			<tr>
				<td>iphone8</td>
				<td>6488</td>
				<td>
					<button>-</button>
					<span>1</span>
					<button>+</button>
				</td>
				<td>6488</td>
			</tr>
		</tbody>
		<tfoot>
			<tr>
				<td colspan="3">总计:</td>
				<td id="total">0</td>
			</tr>
		</tfoot>
	</table>
	
	<script type="text/javascript">
		var buts=document.getElementsByTagName("button");
		for(var i=0;i<buts.length;i++){
			buts[i].onclick=function(){
				if(this.innerHTML=="+"){
					smallprice(this,1);
				}
				
				if(this.innerHTML=="-"){
					
					smallprice(this,-1);
				}
				sum();
				
			}
		}
		sum();
		
		
		//封装总计函数
		function sum(){
				var tbody=document.getElementsByTagName("tbody")[0];
				var trs=tbody.children;
				for(var j=0,sum=0;j<trs.length;j++){
					sum+=parseInt(trs[j].lastElementChild.innerHTML);
				}
				total.innerHTML=sum;
		}
		
		//封装小计函数
		function smallprice(but,num){
			if(num==1){
				//获取数目
				var span=but.previousElementSibling;
				//数目加1
				var spanV=parseInt(span.innerHTML)+num;
				//获取单价
				var price=but.parentNode.previousElementSibling;
				//获取小计
				var smallprice=but.parentNode.nextElementSibling;
				if(spanV>0){
					//将新的数目赋值回去
					span.innerHTML=spanV;
					//计算小计
					smallprice.innerHTML=price.innerHTML*spanV;
					}
			}
			
			if(num==-1){
				//获取数目
				var span=but.nextElementSibling;
				//数目加1
				var spanV=parseInt(span.innerHTML)+num;
				//获取单价
				var price=but.parentNode.previousElementSibling;
				//获取小计
				var smallprice=but.parentNode.nextElementSibling;
				if(spanV>0){
					//将新的数目赋值回去
					span.innerHTML=spanV;
					//计算小计
					smallprice.innerHTML=price.innerHTML*spanV;
				}
			}								
		}
	</script>
	</body>
</html>
